<template>
  <div>
    <el-amap :zoom="zoom" :center="center" class="amap-div" @click="clickMap">
      <el-amap-search-box :visible="true" placeholder="请输入关键字" @select="selectPoi" @choose="choosePoi" />
      <el-amap-control-scale :visible="true" />
      <el-amap-control-hawk-eye :visible="true" />
      <el-amap-control-map-type :visible="true" />
      <el-amap-control-geolocation :visible="true" @complete="getLocation"/>
      <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker.position"/>
    </el-amap>
  </div>
</template>

<script>
export default {
  data() {
    return {
      zoom: 12,
      center: [102.829208, 24.852349],
      markers: [],
      mapPosData: {}
    }
  },
  methods: {
    selectPoi(e) {
      // 刷新点
      const data = e.poi
      if (data) {
        this.marker(data.location.lng, data.location.lat)
      }
    },
    choosePoi(e) {
      console.log('choosePoi: ', e)
    },
    getLocation(e) {
      console.log('getLocation: ', e)
    },
    clickMap(e) {
      const _this = this
      this.marker(e.lnglat.lng, e.lnglat.lat)
    },
    marker(lng, lat) {
      this.markers = []
      const _this = this
      let marker = {
        position: [lng, lat],
        id: new Date().getTime()
      }

      var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: 'all'
      })
      _this.mapPosData.longitude = lng // 经度
      _this.mapPosData.latitude = lat // 纬度
      geocoder.getAddress([lng, lat], function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          if (result && result.regeocode) {
            _this.mapPosData.addressComponent = result.regeocode.addressComponent
            _this.mapPosData.address = result.regeocode.formattedAddress // 具体地址
          }
        }
      })
      this.$emit('map-position', this.mapPosData)
      this.markers.push(marker)
    }
  }
}
</script>

<style lang="scss">
.amap-div {
  margin-bottom: 10px;
  height: 300px;
}

.amap-sug-result {
  z-index: 9999
}
</style>
